#!/usr/bin/env python3
"""
安全管理API路由
提供安全监控、配置和管理功能
"""

from flask import Blueprint, request, jsonify, g
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime
import json

security_bp = Blueprint('security', __name__)

@security_bp.route('/dashboard', methods=['GET'])
@jwt_required()
def get_security_dashboard():
    """获取安全仪表板数据"""
    try:
        # 检查用户权限（这里简化处理，实际应该检查管理员权限）
        current_user = get_jwt_identity()
        
        # 获取安全监控数据
        dashboard_data = g.security_monitor.get_security_dashboard_data()
        
        return jsonify({
            'success': True,
            'data': dashboard_data,
            'timestamp': datetime.utcnow().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取安全仪表板数据失败: {str(e)}',
            'timestamp': datetime.utcnow().isoformat()
        }), 500

@security_bp.route('/threats', methods=['GET'])
@jwt_required()
def get_threat_statistics():
    """获取威胁统计"""
    try:
        hours = request.args.get('hours', 24, type=int)
        
        threat_stats = g.security_monitor.get_threat_statistics(hours)
        
        return jsonify({
            'success': True,
            'data': threat_stats,
            'timestamp': datetime.utcnow().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取威胁统计失败: {str(e)}',
            'timestamp': datetime.utcnow().isoformat()
        }), 500

@security_bp.route('/blacklist', methods=['GET'])
@jwt_required()
def get_blacklist():
    """获取黑名单"""
    try:
        blacklisted_ips = []
        
        # 获取临时黑名单
        for key in g.redis_client.scan_iter(match="security:temp_blacklist:*"):
            ip = key.decode().split(':')[-1]
            reason = g.redis_client.get(key).decode()
            ttl = g.redis_client.ttl(key)
            blacklisted_ips.append({
                'ip': ip,
                'reason': reason,
                'expires_in': ttl,
                'type': 'temporary'
            })
        
        # 获取永久黑名单
        for key in g.redis_client.scan_iter(match="security:blacklist:*"):
            ip = key.decode().split(':')[-1]
            reason = g.redis_client.get(key).decode()
            blacklisted_ips.append({
                'ip': ip,
                'reason': reason,
                'type': 'permanent'
            })
        
        return jsonify({
            'success': True,
            'data': blacklisted_ips,
            'timestamp': datetime.utcnow().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取黑名单失败: {str(e)}',
            'timestamp': datetime.utcnow().isoformat()
        }), 500

@security_bp.route('/blacklist/<ip>', methods=['DELETE'])
@jwt_required()
def remove_from_blacklist(ip):
    """从黑名单移除IP"""
    try:
        # 移除临时黑名单
        g.redis_client.delete(f'security:temp_blacklist:{ip}')
        # 移除永久黑名单
        g.redis_client.delete(f'security:blacklist:{ip}')
        
        # 记录操作
        current_user = get_jwt_identity()
        g.security_monitor._send_alert({
            'alert_type': 'blacklist_removal',
            'ip': ip,
            'operator': current_user,
            'timestamp': datetime.utcnow().isoformat()
        })
        
        return jsonify({
            'success': True,
            'message': f'IP {ip} 已从黑名单移除',
            'timestamp': datetime.utcnow().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'移除黑名单失败: {str(e)}',
            'timestamp': datetime.utcnow().isoformat()
        }), 500

@security_bp.route('/blacklist', methods=['POST'])
@jwt_required()
def add_to_blacklist():
    """添加IP到黑名单"""
    try:
        data = g.decrypted_data if hasattr(g, 'decrypted_data') else request.get_json()
        
        ip = data.get('ip')
        reason = data.get('reason', '手动添加')
        duration = data.get('duration', 3600)  # 默认1小时
        permanent = data.get('permanent', False)
        
        if not ip:
            return jsonify({
                'success': False,
                'message': 'IP地址不能为空',
                'timestamp': datetime.utcnow().isoformat()
            }), 400
        
        if permanent:
            # 添加到永久黑名单
            g.redis_client.set(f'security:blacklist:{ip}', reason)
        else:
            # 添加到临时黑名单
            g.redis_client.setex(f'security:temp_blacklist:{ip}', duration, reason)
        
        # 记录操作
        current_user = get_jwt_identity()
        g.security_monitor._send_alert({
            'alert_type': 'manual_blacklist',
            'ip': ip,
            'reason': reason,
            'duration': duration if not permanent else 'permanent',
            'operator': current_user,
            'timestamp': datetime.utcnow().isoformat()
        })
        
        return jsonify({
            'success': True,
            'message': f'IP {ip} 已添加到黑名单',
            'timestamp': datetime.utcnow().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'添加黑名单失败: {str(e)}',
            'timestamp': datetime.utcnow().isoformat()
        }), 500

@security_bp.route('/whitelist', methods=['GET'])
@jwt_required()
def get_whitelist():
    """获取白名单"""
    try:
        whitelisted_ips = []
        
        for key in g.redis_client.scan_iter(match="security:whitelist:*"):
            ip = key.decode().split(':')[-1]
            reason = g.redis_client.get(key).decode()
            whitelisted_ips.append({
                'ip': ip,
                'reason': reason
            })
        
        return jsonify({
            'success': True,
            'data': whitelisted_ips,
            'timestamp': datetime.utcnow().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取白名单失败: {str(e)}',
            'timestamp': datetime.utcnow().isoformat()
        }), 500

@security_bp.route('/whitelist', methods=['POST'])
@jwt_required()
def add_to_whitelist():
    """添加IP到白名单"""
    try:
        data = g.decrypted_data if hasattr(g, 'decrypted_data') else request.get_json()
        
        ip = data.get('ip')
        reason = data.get('reason', '手动添加')
        
        if not ip:
            return jsonify({
                'success': False,
                'message': 'IP地址不能为空',
                'timestamp': datetime.utcnow().isoformat()
            }), 400
        
        # 添加到白名单
        g.redis_client.set(f'security:whitelist:{ip}', reason)
        
        # 记录操作
        current_user = get_jwt_identity()
        g.security_monitor._send_alert({
            'alert_type': 'whitelist_addition',
            'ip': ip,
            'reason': reason,
            'operator': current_user,
            'timestamp': datetime.utcnow().isoformat()
        })
        
        return jsonify({
            'success': True,
            'message': f'IP {ip} 已添加到白名单',
            'timestamp': datetime.utcnow().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'添加白名单失败: {str(e)}',
            'timestamp': datetime.utcnow().isoformat()
        }), 500

@security_bp.route('/whitelist/<ip>', methods=['DELETE'])
@jwt_required()
def remove_from_whitelist(ip):
    """从白名单移除IP"""
    try:
        g.redis_client.delete(f'security:whitelist:{ip}')
        
        # 记录操作
        current_user = get_jwt_identity()
        g.security_monitor._send_alert({
            'alert_type': 'whitelist_removal',
            'ip': ip,
            'operator': current_user,
            'timestamp': datetime.utcnow().isoformat()
        })
        
        return jsonify({
            'success': True,
            'message': f'IP {ip} 已从白名单移除',
            'timestamp': datetime.utcnow().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'移除白名单失败: {str(e)}',
            'timestamp': datetime.utcnow().isoformat()
        }), 500

@security_bp.route('/config/alerts', methods=['GET'])
@jwt_required()
def get_alert_config():
    """获取告警配置"""
    try:
        config_key = "security:alert_config"
        config_data = g.redis_client.get(config_key)
        
        if config_data:
            alert_config = json.loads(config_data)
        else:
            alert_config = g.security_monitor.alert_config
        
        # 隐藏敏感信息
        safe_config = alert_config.copy()
        if 'email' in safe_config and 'password' in safe_config['email']:
            safe_config['email']['password'] = '***'
        if 'sms' in safe_config and 'api_key' in safe_config['sms']:
            safe_config['sms']['api_key'] = '***'
        
        return jsonify({
            'success': True,
            'data': safe_config,
            'timestamp': datetime.utcnow().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取告警配置失败: {str(e)}',
            'timestamp': datetime.utcnow().isoformat()
        }), 500

@security_bp.route('/config/alerts', methods=['PUT'])
@jwt_required()
def update_alert_config():
    """更新告警配置"""
    try:
        data = g.decrypted_data if hasattr(g, 'decrypted_data') else request.get_json()
        
        # 更新告警配置
        g.security_monitor.configure_alerts(data)
        
        # 记录操作
        current_user = get_jwt_identity()
        g.security_monitor._send_alert({
            'alert_type': 'config_update',
            'config_type': 'alerts',
            'operator': current_user,
            'timestamp': datetime.utcnow().isoformat()
        })
        
        return jsonify({
            'success': True,
            'message': '告警配置已更新',
            'timestamp': datetime.utcnow().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'更新告警配置失败: {str(e)}',
            'timestamp': datetime.utcnow().isoformat()
        }), 500

@security_bp.route('/events', methods=['GET'])
@jwt_required()
def get_security_events():
    """获取安全事件"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 50, type=int)
        event_type = request.args.get('type')
        
        events = []
        
        # 获取安全日志
        for key in g.redis_client.scan_iter(match="security_log:*"):
            log_data = g.redis_client.get(key)
            if log_data:
                try:
                    event = json.loads(log_data)
                    if not event_type or event.get('event_type') == event_type:
                        events.append(event)
                except Exception:
                    continue
        
        # 按时间排序
        events.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
        
        # 分页
        start = (page - 1) * per_page
        end = start + per_page
        paginated_events = events[start:end]
        
        return jsonify({
            'success': True,
            'data': {
                'events': paginated_events,
                'total': len(events),
                'page': page,
                'per_page': per_page,
                'pages': (len(events) + per_page - 1) // per_page
            },
            'timestamp': datetime.utcnow().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取安全事件失败: {str(e)}',
            'timestamp': datetime.utcnow().isoformat()
        }), 500

@security_bp.route('/monitor/status', methods=['GET'])
@jwt_required()
def get_monitor_status():
    """获取监控状态"""
    try:
        status = {
            'running': g.security_monitor.running,
            'stats': g.security_monitor.stats,
            'config': g.security_monitor.monitor_config
        }
        
        return jsonify({
            'success': True,
            'data': status,
            'timestamp': datetime.utcnow().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取监控状态失败: {str(e)}',
            'timestamp': datetime.utcnow().isoformat()
        }), 500

@security_bp.route('/monitor/start', methods=['POST'])
@jwt_required()
def start_monitor():
    """启动监控"""
    try:
        g.security_monitor.start_monitoring()
        
        return jsonify({
            'success': True,
            'message': '安全监控已启动',
            'timestamp': datetime.utcnow().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'启动监控失败: {str(e)}',
            'timestamp': datetime.utcnow().isoformat()
        }), 500

@security_bp.route('/monitor/stop', methods=['POST'])
@jwt_required()
def stop_monitor():
    """停止监控"""
    try:
        g.security_monitor.stop_monitoring()
        
        return jsonify({
            'success': True,
            'message': '安全监控已停止',
            'timestamp': datetime.utcnow().isoformat()
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'停止监控失败: {str(e)}',
            'timestamp': datetime.utcnow().isoformat()
        }), 500